import React, { Fragment, Component } from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import intl from 'react-intl-universal'
import Header from 'containers/header/header.js'
import Footer from 'containers/footer/footer.js'
import navList from 'src/navList.js'
const routeMap = (routes, matchUrl) =>  
    routes.map(({name, path, exact = true, component, children}) => (
        <Route path = { `${ matchUrl ? matchUrl : ''}${path}` } exact = { exact } component = { component ? component : ({match}) => (<Fragment>{routeMap(children, match.url)}</Fragment>) } key = { name }/>
    ))
const locales = {
    "en-US": require('constants/intl-local/en-US.js'),
    "zh-CN": require('constants/intl-local/zh-CN.js'),
    "ja-JP": require('constants/intl-local/ja-JP.js'),
}
const languages = [{btn: '简',name: 'zh-CN'}, {btn: '日',name: 'ja-JP'}, {btn: 'EN',name: 'en-US'}]
let currentIndex
export default (routes) => class RouterMap extends Component {
    constructor() {
        super()
        this.state = {
            initDone: false
        }
    }
    componentDidMount() {
        this._loadLocales()
    }
    _loadLocales() {
        let matching = window.location.search.match(/lang=(\S*)(&)?/)
        if (matching === null) {
            currentIndex = 0
        } else {
            currentIndex = languages.findIndex(item => item.name === matching[1])
            if (currentIndex === -1)currentIndex = 0
        }
        let currentLocale = languages[currentIndex].name
        intl.init({
            currentLocale,
            locales
        })
        .then(() => {
            this.setState({
                initDone: true
            })
        })
    }
    render() {
        return this.state.initDone &&
            (<IntlContext.Provider value={{languages, currentIndex}}>
                <Router>
                    <Fragment>
                        <Header navList={navList}/>
                            <main className="router-container">
                                <Switch>
                                    {
                                        routeMap(routes)
                                    }
                                </Switch>
                            </main>
                        <Footer/>
                    </Fragment>
                </Router>
            </IntlContext.Provider>)
    }
}
export const IntlContext = React.createContext({
    languages,
    currentIndex
})
